﻿#include <iostream>
#include <fstream>
#include <string>
#include <corecrt_io.h>
#include <windows.h>
#include <tchar.h>

#include "cat-app.hpp"

static char* startUpConfig[1] = { R"({
	"decoration" : 
	{
		"armLineColor" : 
		[
			0,
			0,
			0
		],
		"hand_offset" : 
		[
			0,
			0
		],
		"l2d_correct" : 1.075700044631958,
		"l2d_offset" : 
		[
			-0.0,
			-0.0095739997923374176
		],
		"window_size" : 
		[
			612,
			352
		]
	},
	"main_decoration" : 
	{
		"framerateLimit" : 60,
		"gamepad_ID" : 3,
		"input_mode" : 1,
		"is_mouse_through" : false,
		"l2d" : true,
		"l2d_random_expression" : false,
		"l2d_random_motion" : false,
		"l2d_spead" : 0.74540001153945923,
		"motion_keep" : true,
		"mouse_force_move" : false,
		"mouse_horizontal_flip" : false,
		"mouse_speed" : 10.0,
		"mouse_vertical_flip" : false,
		"rgb" : 
		[
			0,
			0,
			0,
			64
		],
		"silent" : false,
		"sound_keep" : true,
		"topWindow" : false,
		"window_handle" : 0,
		"window_size" : 
		[
			405,
			232
		]
	},
	"plugins" : 
	{
		"mode" : 1,
		"mode_ex" : 
		[
		],
		"module" : 
		[			
		]
	}
})" };

using namespace std;

static int run_program(fstream& logFile, int argc, char* argv[]) {
	int ret = -1;
	
	CATApp program(argc, argv);
	try {
		program.APPInit();

		ret = program.Run();
	
	}
	catch (const char* error) {
		
	
	}
	program.APPRelease();

	return ret;
};

static inline bool arg_is(const char* arg, const char* long_form,
	const char* short_form)
{
	return (long_form && strcmp(arg, long_form) == 0) ||
		(short_form && strcmp(arg, short_form) == 0);
}

bool IsElevated() {
	BOOL fRet = FALSE;
	HANDLE hToken = NULL;
	if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {
		TOKEN_ELEVATION Elevation;
		DWORD cbSize = sizeof(TOKEN_ELEVATION);
		if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &cbSize)) {
			fRet = Elevation.TokenIsElevated;
		}
	}
	if (hToken) {
		CloseHandle(hToken);
	}
	return fRet;
}

int DisplayNotAdminMessageBox()
{
	int msgboxID = MessageBox(
		NULL,
		(LPCWSTR)L"没有以管理员权限运行会无法获取超出权限的\n键盘鼠标输入,是否以管理员权限重新启动?",
		(LPCWSTR)L"警告",
		MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2
	);

	switch (msgboxID)
	{
	case IDCANCEL:
		exit(0);
		break;
	case IDTRYAGAIN:
	{
		ShellExecute(NULL, L"runas", L"cat.exe", 0, 0, SW_SHOWNORMAL);
		exit(0);
	}
	break;
	case IDCONTINUE:
		break;
	}

	return msgboxID;
}

int main(int argc, char* argv[]) {

#ifndef _DEBUG
#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
#endif // DEBUG


	bool checkAdmin = IsElevated();
	if (!checkAdmin)
		DisplayNotAdminMessageBox();

	for (int i = 1; i < argc; i++) {
		if (arg_is(argv[i], "--help", "-h")) {
			std::cout
				<< "--help, -h: Get list of available commands.\n\n";
			exit(0);
		}
		else if (arg_is(argv[i], "--version", "-V")) {
			exit(0);
		}
	}
	fstream logFile;	

	int ret = run_program(logFile, 1, startUpConfig);

	return ret;
}